import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {//存放状态
    //  存放的键值对就是所要管理的状态
    name: 'hello VueX',
    count: 0,
    sex: '男',
    todos: [
      {id: 1, text: 'toDo001', done: true},
      {id: 2, text: 'toDo002', done: false}
    ]
  },
  mutations: {//操作state
    edit(state){
      state.name = '你好，VurX！'
    },
    increment(state, param) {
      state.count = param.param.num || ++state.count
      if (param.param.age) {
        // Vue.set 为某个对象设置成员的值，若不存在则新增
        Vue.set(state, "age", param.param.age)
        // Vue.delete 删除成员
        Vue.delete(state, "sex")
      }
    },
    handleTodo(state, index) {
      state.todos[index].done = !state.todos[index].done;
    }
  },
  getters: {//加工state成员
    nameInfo(state) {
      return "我是在vuex中定义的名字：" + state.name
    },
    doneTodos: state => {
      let arr = state.todos.filter((item, index, arr) => {
        return item.done
      })
      return arr
    },

  },
  actions: {//异步操作
    changeName(context,payload){
      return new Promise((resolve,reject)=>{
        setTimeout(()=>{
          context.commit('edit',payload)
          resolve()
        },2000)
      })
    }

  },
  modules: {//模块化状态管理

  }
})

export default store
